<?php

declare(strict_types=1);


namespace app\controller\mini;

use app\controller\admin\AdminBaseController;
use app\Request;
use app\model\admin\SysMember;
use app\model\mini\BalanceLog;
use app\model\mini\MiniUser;
use app\model\mini\MiniUserRelation;
use app\service\JwtAuth;
use think\facade\Db;

class MiniUserController extends AdminBaseController
{
    public function getUserSession(Request $request)
    {
        // $user_id  = $->sys_user_id;
        $code = input('code');
        $op_id = input('op_id');
        $parent_id = input('parent_id'); //上级id

        if (!$code) {
            return error('失败');
        }
        $res = $this->miniApp->auth->session($code);

        $info = MiniUser::where('openid', $res['openid'])->find();

        if ($info) {
            $id = $info->id;
            $user_id = $info->id;
            $is_old = true;
            $info->session_key = $res['session_key'];
            $info->save();
        } else {
            // 绑定上下级
            $data = [
                "openid" => $res['openid'],
                "session_key" => $res['session_key']
            ];
            if ($op_id) {
                $data['op_id'] = $op_id;
                // 上级是运营商，标记自身为代理商
                $data['type'] = 1;
                $data['remark'] = "扫码运营商(" . $op_id . ")的二维码创建";
                $newUser = MiniUser::create($data);
                $user_id = $newUser->id;
            } else {
                Db::startTrans();
                try {

                    $newUser = MiniUser::create($data);
                    $newUserId = $newUser->id;
                    $user_id = $newUser->id;
                    $newData = [];
                    $newData['remark'] = "普通用户进入小程序创建";
                    // 不存在 op_id 
                    if ($parent_id) {

                        $p_info = MiniUser::find($parent_id);
                        if ($p_info) {
                            if ($p_info->type == 1) {
                                //上级是代理商
                                $newData['agent_level'] = 1;
                                $newData['agent_id'] = $p_info->id;
                                $newData['op_id'] = $p_info->op_id;
                                $newData['pid'] = $parent_id;
                                $newData['type'] = 2; //上级不是运营商，自身只能是商户
                                $newData['remark'] = "扫码代理商(" . $p_info->id . ")的二维码创建";
                            } else {
                                // 上级是普通商户
                                // 添加关联表
                                MiniUserRelation::create([
                                    "parent_id" => $parent_id,
                                    "child_id" => $newUserId,
                                    "level" => 1
                                ]);
                                $newData['remark'] = "扫码普通用户(" . $parent_id . ")的二维码创建";
                                $newData['pid'] = $parent_id;
                                // 查询是否有上级
                                if ($p_info->pid) {
                                    $p_p_info = MiniUser::find($p_info->pid);
                                    if ($p_p_info) {
                                        // 存在上级
                                        if ($p_p_info->type == 1) {
                                            // 上级的上级是代理商
                                            $newData['agent_level'] = 2;
                                            $newData['agent_id'] = $p_info->id;
                                            $newData['op_id'] = $p_info->op_id;
                                            $newData['pid'] = $parent_id;
                                            $newData['type'] = 2; //上级不是运营商，自身只能是商户 
                                        } else {
                                            // 上上级是商户，绑定关联
                                            MiniUserRelation::create([
                                                "parent_id" => $p_p_info->id,
                                                "child_id" => $newUserId,
                                                "level" => 2
                                            ]);
                                            $newData['remark'] = "扫码普通用户(" . $parent_id . ")的二维码创建";

                                            // 判断上上级是否有上级
                                            if ($p_p_info->pid) {
                                                // 存在上上上级
                                                $p_p_p_info = MiniUser::find($p_p_info->pid);
                                                if ($p_p_p_info->type == 1) {
                                                    // 上上上级是代理商
                                                    $newData['agent_level'] = 3;
                                                    $newData['agent_id'] = $p_info->id;
                                                    $newData['op_id'] = $p_info->op_id;
                                                    $newData['pid'] = $parent_id;
                                                    $newData['type'] = 2; //上级不是运营商，自身只能是商户 
                                                } else {
                                                    // 上上上级是商户不做处理
                                                    //即使是商户也不记录，超过2级
                                                }
                                            }
                                        }
                                    }
                                } else {
                                }
                            }
                        } else {
                            // 上级不存在
                        }
                    }
                    // 重新修改用户表
                    if (count($newData)) {
                        Db::table('mini_user')->where('id', $newUserId)->update($newData);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }
            $id = $user_id;
            $is_old = false;
        }
        // 返回token
        $token = JwtAuth::createToken($id, "mini_user");

        return success([
            'token' => $token, "is_old" => $is_old
        ], "登录成功");
    }
    public function getUserInfo(Request $request)
    {
        $user_id = $request->user_id;
        $info = MiniUser::find($user_id);
        return success($info);
    }
    public function getUserPhone(Request $request)
    {
        $params = $request->param();
        $user_id = $request->user_id;
        $info = MiniUser::find($user_id);
        // $codeRes = $this->miniApp->auth->session($params['code']);
        // var_dump($codeRes);
        // $phoneRes = $this->miniApp->encryptor->decryptData($codeRes['session_key'], $params['iv'], $params['encryptedData']);

        $phoneRes = $this->miniApp->phone_number->getUserPhoneNumber($params['code']);
        // var_dump($phoneRes);
        if ($phoneRes['errcode'] == 0) {
            $phone = $phoneRes['phone_info']['purePhoneNumber'];
            // 保存
            $info->mobile = $phone;


            $info->save();
            return success();
        } else {
            return error($phoneRes['errmsg']);
        }
    }
    public function setUserInfo(Request $request)
    {
        $avatar = input('avatar');
        $avatar_url = input('avatar_url');
        $nickname = input('nickname');
        $user_id = $request->user_id;
        $info = MiniUser::find($user_id);
        $info->nickname = $nickname;
        $info->avatar = $avatar;
        $info->avatar_url = $avatar_url;

        $info->save();
        return success();
    }

    public function myReward(Request $request)
    {
        $created_at = input('time');
        $user_id = $request->user_id;
        $user = MiniUser::find($user_id);
        if (strlen($created_at) == 13) {
            // 传毫秒转换为妙
            $created_at = $created_at / 1000;
        }
        $where = function ($q) use ($created_at) {
            if ($created_at) {
                $q->whereBetweenTime('created_at', $created_at, $created_at + 60 * 60 * 24);
            }
        };
        // if ($created_at) {
        //     $paginator = BalanceLog::where([
        //         'phone' => $user->phonenumber,
        //     ])->where('profit_type', '!=', 9)->whereBetween('created_at', [$created_at, $created_at + 60 * 60 * 24])->orderBy('created_at', 'desc')->paginate($this->pageSize);
        // } else {
        //     $paginator = BalanceLog::where([
        //         'phone' => $user->phonenumber,
        //     ])->where('profit_type', '!=', 9)->orderBy('created_at', 'desc')->paginate($this->pageSize);
        // }
        // 
        $paginator = BalanceLog::where([
            'user_id' => $user->id,
        ])->where('profit_type', '<>', 9)->where($where)->order('created_at', 'desc')
            ->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        $sumMoney = BalanceLog::where([
            'user_id' => $user->id,
        ])->where('profit_type', '<>', 9)->sum('money');

        return success([
            'sumMoney' => $sumMoney,
            'items' => $paginator->items(),
            'pageSize' => $paginator->listRows(),
            'pageNum' => $paginator->currentPage(),
            'total' => $paginator->total(),
            'totalPage' => $paginator->lastPage(),
        ]);
    }
    public function getFensList(Request $request)
    {
        $type = input('type', 1); //1直推2间推
        // $officialUser = $request->officialUser;
        // $user_id = $officialUser['user_id'];
        $user_id = $request->user_id;
        // MpUserRelation::where('leavel', 1);
        $res = MiniUserRelation::where('parent_id', $user_id)
            ->with(['childUser' => function ($q) {
                $q->field('id,nickname,headimgurl,create_at');
            }])
            ->where('level', $type)
            ->field("id,child_id,created_at")
            ->order('id', 'desc')->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        return successPage($res);
    }
}
